package com.kehutong.admin.controler.app;

import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.execute.entity.FindPage;
import org.coraframework.util.Objects;

import com.kehutong.admin.entity.Role;
import com.kehutong.admin.entity.User;
import com.kehutong.admin.entity.app.AppRole;
import com.kehutong.admin.util.UserUtils;
import com.kehutong.common.util.Token;

@MvcAction
@ReqMapping("/admin/app/role")
public class AppRoleController {

    @Inject
    private JdbcSession jdbcSession;


//    @HasPermission("app:role:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
    	FindPage<AppRole> find = jdbcSession.findPage(AppRole.class)
    			.eq("deleted", false)
				.like(jsonObject, "name");
    	
    	final User user = UserUtils.getUser();
		if (user.isAdmin() || user.isAdminRole() || Objects.isEmpty(user.getCompanyNo())) {
			find.isNull("companyNo");
		} else {
			find.eq("companyNo", user.getCompanyNo());
		}
		
        return find.page(jsonObject).exe();
    }

    @HasPermission("app:role:view")
    @ReqMapping("/get")
    public Object getById(Role role) {
        return role;
    }

    @Bean(newInstance=true, copy=true)
    @HasPermission("app:role:edit")
    @ReqMapping("/save")
    public Object save(Token token, AppRole role) {
    	role.setCompanyNo(token.getCompanyNo());
		jdbcSession.insert(role);
    	
        return Result.success();
    }

    @HasPermission("app:role:edit")
    @ReqMapping("/update")
    public Object update(Token token, AppRole role) {
    	role.setCompanyNo(token.getCompanyNo());
		jdbcSession.updateById(role);
		return Result.success();
    }

    @HasPermission("app:role:edit")
    @ReqMapping("/delete")
    public Object deleteById(Role role) {
    	role.setDeleted(true);
    	jdbcSession.updateById(role);

        return Result.success();
    }
}
